package com.lagou.client;

import com.lagou.server.service.entity.RpcRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

//    private static UserClientHandler userClientHandler;

    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass){
        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法


//                if(userClientHandler == null){
//                 initClient();
//                }
                UserClientHandler userClientHandler = RpcClients.getUserClientHandler();
                if(userClientHandler == null) {
                    System.out.println("没有可用的服务端，请检查服务端是否启动");
                    return null;
                }
                System.out.println("调用的RPC服务端为：" + userClientHandler.getRpcServer());

                // 设置参数
//                userClientHandler.setPara(providerName+args[0]);
                // 构造RpcRequest对象
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setRequestId(UUID.randomUUID().toString());
                rpcRequest.setClassName(serviceClass.getCanonicalName());
                rpcRequest.setMethodName(method.getName());

                Class<?>[] parameterTypes = method.getParameterTypes();
                rpcRequest.setParameterTypes(parameterTypes);
                rpcRequest.setParameters(args);

                System.out.println("发送请求对象：" + rpcRequest);

                userClientHandler.setRpcRequest(rpcRequest);

                // 去服务端请求数据
                return executor.submit(userClientHandler).get();
            }
        });


    }






}
